package main

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"log"
	"os"
	"time"
)

func main() {
	cronTest()
	//RunCron()
}

func cronTest() {
	c := cron.New(cron.WithSeconds())

	// 添加定时任务
	_, err := c.AddFunc("*/3 * * * * *", func() {
		fmt.Println("执行定时任务,time is ", time.Now())
		// 程序运行一段时间后停止定时任务
		//time.Sleep(2 * time.Second)
		//c.Stop()
	})

	if err != nil {
		fmt.Println("添加定时任务失败：", err)
		return
	}

	// 启动定时任务
	c.Start()
	select {}

}

func RunCron() {
	c := cron.New(cron.WithSeconds(), cron.WithChain(cron.SkipIfStillRunning(cron.DefaultLogger)), cron.WithLogger(
		cron.VerbosePrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags))))
	i := 1
	EntryID, err := c.AddFunc("*/5 * * * * *", func() {
		fmt.Println(time.Now(), "每5s一次----------------", i)
		time.Sleep(time.Second * 6)
		i++
	})
	fmt.Println(time.Now(), EntryID, err)

	c.Start()
	select {}
}
